package com.czmini.cztest.service.impl;

import com.czmini.cztest.dao.ZcTestJenkinsMapper;
import com.czmini.cztest.dao.ZcTestTaskMapper;
import com.czmini.cztest.dto.AllureReportDto;
import com.czmini.cztest.dto.ResultDto;
import com.czmini.cztest.dto.TokenDto;
import com.czmini.cztest.entity.ZcTestJenkins;
import com.czmini.cztest.entity.ZcTestTask;
import com.czmini.cztest.service.ZcTesReportService;
import com.czmini.cztest.util.ReportUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @ProjectName: cztest
 * @Package: com.czmini.cztest.service.impl
 * @ClassName: ZcTesReportServiceImpl
 * @Author: 还是那个橙子
 * @Description:
 * @Date: 2022/5/14 23:57
 * @Version: 1.0
 */
@Service
@Slf4j
public class ZcTesReportServiceImpl implements ZcTesReportService {
    @Autowired
    private ZcTestTaskMapper zcTestTaskMapper;

    @Autowired
    private ZcTestJenkinsMapper zcTestJenkinsMapper;


    @Override
    public ResultDto<AllureReportDto> getAllureReport(TokenDto tokenDto, Integer taskId) {
        ZcTestTask queryTestTask = new ZcTestTask();
        queryTestTask.setId(taskId);
        queryTestTask.setCreateUserId(tokenDto.getUserId());

        ZcTestTask resultTestTask = zcTestTaskMapper.selectOne(queryTestTask);
        if (resultTestTask == null) {
            return ResultDto.fail("没有找到对应的任务"+taskId);
        }
        String buildUrl = resultTestTask.getBuildUrl();
        if(StringUtils.isEmpty(buildUrl)){
            return ResultDto.fail("测试任务的构建地址不存在 "+taskId);
        }

        Integer testJenkinsId = resultTestTask.getTestJenkinsId();
        if(Objects.isNull(testJenkinsId)){
            return ResultDto.fail("测试任务的jenkinsId不存在 "+taskId);
        }
        ZcTestJenkins queryTestJenkins = new ZcTestJenkins();
        queryTestJenkins.setId(testJenkinsId);
        queryTestJenkins.setCreateUserId(tokenDto.getUserId());
        // 查询Jenkins
        ZcTestJenkins resultTestJenkins = zcTestJenkinsMapper.selectOne(queryTestJenkins);
        // 获取报告地址
        String allureReportUrl = ReportUtil.getAllureReportUrl(buildUrl,resultTestJenkins,true);
        // 获取报告实体
        AllureReportDto allureReportDto = new AllureReportDto();
        allureReportDto.setTaskId(taskId);
        allureReportDto.setAllureReportUrl(allureReportUrl);
        return ResultDto.success("成功", allureReportDto);
    }
}
